import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/utils/eventbus.dart';
import 'package:flutter_enjoy_plus/utils/http.dart';
import 'package:flutter_enjoy_plus/utils/logger.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo = {'avatar': '', 'nickName': ''};

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {};

  final _nameController = TextEditingController();

  @override
  void initState() {
    setState(() {
      // 获取父组件传参的头像
      userInfo = widget.userInfo;
      // 获取父组件传参的昵称
      _nameController.text = userInfo['nickName'];
    });
    super.initState();
  }

// 修改图片
  _selectAvatar() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 120,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    _pickImageFromGalleryorCamera('camera');
                    // ToastUtil.showInfo('点击拍照');
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    // ToastUtil.showInfo('点击相册');
                    if (kIsWeb) {
                      ToastUtil.showInfo('web运行');
                    } else if (Platform.isAndroid) {
                      ToastUtil.showInfo('安卓端运行');
                      // 从相册选择图片
                      _pickImageFromGalleryorCamera('gallery');
                    }
                  },
                )
              ]));
        });
  }

// 从相册选择图片
  _pickImageFromGalleryorCamera(String text) async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(
        source: text == 'gallery' ? ImageSource.gallery : ImageSource.camera);
    if (pickedFile != null) {
      // logger.i(pickedFile);
      try {
        FormData formData = FormData.fromMap({
          'file': await MultipartFile.fromFile(pickedFile.path),
          'type': 'avatar'
        });
        final res = await http.post('/upload', formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传头像失败');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
      } finally {
        // 关闭蒙层
        Navigator.pop(context);
      }
    }
  }

// 更新昵称
  updateNickName() async {
    if (_nameController.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    try {
      await http.put('/userInfo', {"nickName": _nameController.text});
      setState(() {
        userInfo['nickName'] = _nameController.text;
        ToastUtil.showSuccess('修改成功!');
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(
          onPressed: () {
            eventBus.fire(BackMine());
            Navigator.pop(context);
          },
          icon: const Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        // ToastUtil.showInfo('点击了头像');
                        _selectAvatar();
                      },
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: userInfo['avatar'] != ''
                              ? Image.network(userInfo['avatar'],
                                  width: 30, height: 30)
                              : Image.asset('images/avatar_1.jpg',
                                  width: 30, height: 30)),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                    controller: _nameController,
                    decoration: const InputDecoration(
                        hintText: '请输入昵称', border: InputBorder.none),
                    textAlign: TextAlign.right,
                    onEditingComplete: () {
                      updateNickName();
                    }),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
